<template>
  <div class="user-info-form asset-info-form">
    <el-form v-loading="loading" label-width="150px" :model="videoInfoForm" :rules="videoInfoFormRules" ref="videoInfoForm" @submit.native.prevent>
      <el-form-item label="设备编码：" prop='deviceId'>
        <el-input
          v-model="videoInfoForm.deviceId"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="设备名称：" prop='name'>
        <el-input
          v-model="videoInfoForm.name"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="设备类型：" prop='type'>
        <el-select  v-model="videoInfoForm.type">
          <el-option
            v-for="item in deviceTypeList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="通道号：" prop='channel'>
        <el-input
          v-model="videoInfoForm.channel"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="是否连接外网：" prop='internetAccess'>
        <el-radio-group v-model="videoInfoForm.internetAccess">
          <el-radio label="0">是</el-radio>
          <el-radio label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="封面是否同步：" prop='synchroThumbnail'>
        <el-radio-group v-model="videoInfoForm.synchroThumbnail">
          <el-radio label="0">同步</el-radio>
          <el-radio label="1">不同步</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="封面：" prop='picUrl'>
        <el-upload
          :action="QINIUUPLOADURL"
          :multiple="false"
          ref="upload"
          list-type="picture-card"
          :data="qiniuData"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemovePic"
          :on-error="handleError"
          :before-upload="beforeAvatarUpload"
          :on-preview="$imgPreview"
          :file-list="qiniuData.fileList"
          :limit="1"
          :on-exceed="handleExceed"
          accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="监控类型：" prop='shape'>
        <el-select  v-model="videoInfoForm.shape">
          <el-option
            v-for="item in shapeTypeList"
            :key="item.dictKey"
            :label="JSON.parse(item.dictValue).name"
            :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频位置类型：" prop='positionType'>
        <el-select  v-model="videoInfoForm.positionType">
          <el-option
            v-for="item in positionTypeList"
            :key="item.dictKey"
            :label="item.dictValue"
            :value="item.dictKey">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否在线："  prop='isOnline'>
        <el-select v-model="videoInfoForm.isOnline">
          <el-option label="是" value=1></el-option>
          <el-option label="否" value=0></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否加密："  prop='isEncrypt'>
        <el-select v-model="videoInfoForm.isEncrypt">
          <el-option label="是" value=1></el-option>
          <el-option label="否" value=0></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频控制："  prop='isCtrl'>
        <el-select v-model="videoInfoForm.isCtrl">
          <el-option label="是" value=1></el-option>
          <el-option label="否" value=0></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频配置："  prop='authId'>
        <el-select v-model="videoInfoForm.authId">
          <el-option v-for="o in configList" :key="o.id" :label="o.authName" :value="o.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="0" class="verifyidentity-button">
        <el-button @click.stop="closeFun(false)" round>取消</el-button>
        <el-button type="primary" @click="saveGridInfo('videoInfoForm')" round>保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { qnToken } from '@/api/api'
import util from '@/utils/util'
import { getDictByCode } from '@/api/dic'
import { updateVeidoSet,getAuth } from '@/api/sysConfig'

export default {
    name: 'videoInfo',
    // 引入子组件
    components: {

    },
    props: {
      videoInfo: {
        type: Object
      },
      closeFun: {
        type: Function,
        required: true
      },
      orgId:{
        type: Number
      }
    },
    data(){
      return {
        configList:[],
        loading: false,
        qiniuData:{//上传图片携带的参数
          token : "",
          key : "",
          fileList:[],
        },
        deviceTypeList:[],
        shapeTypeList:[],
        positionTypeList:[],
        // 表单数据
        videoInfoForm: {
          channel: '',
          deviceId: '',
          typeName: '',
          internetAccess: '0',
          synchroThumbnail: '0',
          id: '',
          isCtrl: "1",
          isEncrypt: "1",
          isOnline: "1",
          latitude: '',
          longitude: '',
          name: '',
          organizationId: '',
          picUrl: '',
          positionType: '',
          shape: '',
          type: '',
          authId:''
        },
        // 表单校验
        videoInfoFormRules: {
          deviceId: [
            { required: true, message: '请输入设备编码', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入设备名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择设备类型', trigger: 'blur' }
          ],
          channel: [
            { required: true, message: '请输入通道号', trigger: 'blur' }
          ],
          authId: [
            { required: true, message: '请选择视频配置', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      let that = this
      getAuth({
        organizationId: that.orgId,
        equiptType: 0
      }).then(res => {
        that.configList = res.data
      })
      // 获取token
      that.getToken()
      // 获取设备类型
      getDictByCode({
        code: 33
      }).then(res => {
        if(res.status = 200) {
          that.deviceTypeList = res.data.dictValueObj
          if(that.videoInfo.id ==null && that.deviceTypeList.length>0){
              that.videoInfoForm.type = that.deviceTypeList[0].dictKey
          }
        }
      })
      // 获取监控类型
      getDictByCode({
        code: 54
      }).then(res => {
        if(res.status = 200) {
          that.shapeTypeList = res.data.dictValueObj
          if(that.videoInfo.id ==null && that.shapeTypeList.length>0){
            that.videoInfoForm.shape = that.shapeTypeList[0].dictKey
          }
        }
      })
      // 获取视频位置类型
      getDictByCode({
        code: 73
      }).then(res => {
        if(res.status = 200) {
          that.positionTypeList = res.data.dictValueObj
          if(that.videoInfo.id ==null && that.positionTypeList.length > 0){
            that.videoInfoForm.positionType = that.positionTypeList[0].dictKey
          }
        }
      })
      // 如果有历史值，设置回显
      if(that.videoInfo.id) {
        that.videoInfoForm.authId = that.videoInfo.authId||''
        that.videoInfoForm.deviceId = that.videoInfo.deviceId
        that.videoInfoForm.id =  that.videoInfo.id
        that.videoInfoForm.channel = that.videoInfo.channel
        that.videoInfoForm.typeName = that.videoInfo.typeName
        that.videoInfoForm.isCtrl = that.videoInfo.isCtrl+""
        that.videoInfoForm.isEncrypt = that.videoInfo.isEncrypt+""
        that.videoInfoForm.isOnline = that.videoInfo.isOnline+""
        that.videoInfoForm.name = that.videoInfo.name
        that.videoInfoForm.organizationId = that.videoInfo.organizationId
        that.videoInfoForm.picUrl = that.videoInfo.picUrl
        that.videoInfoForm.internetAccess = String(that.videoInfo.internetAccess)
        that.videoInfoForm.synchroThumbnail = String(that.videoInfo.synchroThumbnail)
        // 设置上传图片初始值
        that.videoInfo.picUrl ? $.each(that.videoInfo.picUrl.split(','), (index,url) => {
            that.qiniuData.fileList.push({
                name: that.videoInfo.name + index,
                url:url
            })
        }) : ''
        that.videoInfoForm.positionType = that.videoInfo.positionType==null?"":that.videoInfo.positionType+""
        that.videoInfoForm.shape = that.videoInfo.shape+""
        that.videoInfoForm.type = that.videoInfo.type+""
      }else{
        that.videoInfoForm.organizationId = that.orgId
      }
    },
    methods: {
      getToken(){  //上传之前获取 token
        qnToken({}).then((result) => {
          this.qiniuData.token= result.data
        })
      },
      beforeAvatarUpload: function(file){//重命名和校验
        var fielLocal = file.name.split(".")
        var fielType = "." + fielLocal[fielLocal.length-1]
        var fielLocalName = fielLocal[0]
        this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType   
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isJPG && !isPNG) {
          this.$message.error("图片只能是 JPG/PNG 格式!");
          return false;
        }
        if (!isLt20M) {
          this.$message.error("图片大小不能超过 20MB!");
          return false;
        }
      },
      handleAvatarSuccess: function(res, file, fileList) {//上传成功
        this.qiniuData.fileList = fileList;
      },
      handleRemovePic: function(file, fileList) {//删除成功
        this.qiniuData.fileList = fileList;
      },
      handleError: function(res) {
        this.$message({
          message: "上传失败",
          duration: 2000,
          type: "warning"
        });
      },
      handleExceed(files, fileList) {//文件超出个数限制时的钩子
        this.$message.warning(`只能上传一张图片！`);
      },
      // 保存
      saveGridInfo(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        let type = 1
        let parames = {}
        // 校验表单
        that.$refs[formName].validate((valid) => {
          if(valid) {
            var parames = {
              authId : that.videoInfoForm.authId,
              channel : that.videoInfoForm.channel,
              deviceId : that.videoInfoForm.deviceId,
              isCtrl: that.videoInfoForm.isCtrl,
              organizationId: that.videoInfoForm.organizationId,
              isEncrypt: that.videoInfoForm.isEncrypt,
              isOnline: that.videoInfoForm.isOnline,
              latitude: that.videoInfoForm.latitude,
              longitude: that.videoInfoForm.longitude,
              name: that.videoInfoForm.name,
              internetAccess: that.videoInfoForm.internetAccess,
              synchroThumbnail: that.videoInfoForm.synchroThumbnail,
              picUrl: util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString(),
              positionType: that.videoInfoForm.positionType,
              shape: that.videoInfoForm.shape,
              type: that.videoInfoForm.type,
              id: that.videoInfo.id
            }

            if(parames.id == null || parames.id == "") {
               parames.id = 0
            }
            // 调用保存接口
            updateVeidoSet(parames).then(res => {
              if(res.status === 200) {
                that.$message({
                  message: '保存成功！',
                  type: 'success'
                })
                // 关闭弹框
                that.closeFun(true)
              } else {
                that.$message({
                  message: res.info,
                  type: 'warning'
                })
              }
            })
          } else {
              return false
          }
        })
      }
    }
  }
</script>
